import requests
import datetime
import time
import json
import os
import logging
import pandas as pd
import threading
from socket import *


# config读取
config = json.loads(open(r'checkConfig.json', encoding='utf-8').read())
# 消息推送
HOST = config["sendIP"]
PORT = config["sendPort"]
# 监控ID
monitor = config["monitor"]
ADDR = (HOST, PORT)
servers = None


# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('see.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)


# 检查系统是否还存活 true 还存活， false 已经关闭
def checkWeb(checkUrl):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0'}
        response = requests.get(url=checkUrl, timeout=2, headers=headers)  # 请求超时时间为2秒
        code = response.status_code  # http请求的返回状态，若为200则表示请求成功,返回的状态码是 int类型
        if code == 200:
            return True
        else:
            return False
    except:
        return False


# 读取Tomcat监控的配置
def readTomcatConfig():
    file = open(r'checkConfig.json', encoding='utf-8')
    res = file.read()
    global servers
    servers = json.loads(res)["servers"]


def sendMSG(msg):
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "forward", "monitor": monitor, "msg": msg}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------sendMSG')
        print('请求失败，继续请求')


# 主函数
def mainApp():
    readTomcatConfig()
    for item in servers:
        if not checkWeb(item["checkUrl"]):
            sendMSG(item["name"] + "出现访问失败，请及时查看服务运行状态")


# start 方法
def start():
    try:
        do = threading.Thread(target=mainApp, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        logger.error(str(r) + '--------start')
    finally:
        threading.Timer(10, start, ()).start()


def selfHeart():
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "heart", "monitor": monitor}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------selfHeart')
    finally:
        threading.Timer(60, selfHeart, ()).start()


threading.Thread(target=selfHeart, ).start()
start()
sendMSG('服务存活状态推送启动')